# -*- coding:utf-8 -*-

'''eof
name:申请人未结清对外担保五级分类校验
code:Ind_UnpaidGuaranClass5Sate_Check
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

'''
对外贷款担保信息 ICRLoanGuarantee

担保贷款本金余额 GuaranteeBalance
担保贷款五级分类 Class5State

指标值=五级分类 IN (“关注”, “次级”, “可疑”, “损失”)的对外担保贷款本金余额之和
'''


import sys
import json
reload(sys)
sys.setdefaultencoding('utf-8')


def ConvertDataType(data_value, data_type):
    return_data = None
    if data_type == 'float':
        try:
            return_data = float(data_value) if float(data_value) >= 0 else None
        except:
            return_data = None
    elif data_type == 'None':
        return_data = 0 if data_value is None else data_value
    return return_data


def Ind_UnpaidGuaranClass5Sate_Check():
    null_type_list = ['', None, 'null', '/', 'Null', 'NULL','--','-']
    count = []
    care_fivestate = [u"关注", u"次级", u"可疑", u"损失"]
    non_fivestate = [u"正常", u"未知"]
    fivestate_type = care_fivestate + non_fivestate
    try:
        if IC in null_type_list:
            return u'缺失值'
        if len(IC) == 0:
            return u'缺失值'
        icr = json.loads(IC[0]["icr"])
        if icr in null_type_list:
            return u'缺失值'
        if len(icr) == 0:
            return u'缺失值'
        if icr.has_key('ICRLoanGuarantee') and len(icr['ICRLoanGuarantee']) >= 1:
            for i in icr['ICRLoanGuarantee']:
                if i.has_key('Class5State') and  i.has_key('GuaranteeBalance')and i['GuaranteeBalance'] not in null_type_list:
                       if  i['Class5State'] in care_fivestate :
                            count.append(ConvertDataType(i['GuaranteeBalance'], 'float'))
                       else:
                            count.append(False)
                else:
                    count.append(None)
        else:
            return u'缺失值'
        #若count均为None,则返回缺失值,否则将None置为0
        balance_count = filter(lambda x: x is not None, count)
        False_count=filter(lambda x:x is not False,balance_count)
        if False_count==0:
            return 0
        else:
            return sum(balance_count) if len(balance_count) != 0 else u'缺失值'

    except:
        return u'缺失值'


result = Ind_UnpaidGuaranClass5Sate_Check()